package io.gitee.kotle.android.utils

import android.content.Context
import android.content.res.Configuration
import android.os.Build
import android.os.LocaleList
import io.gitee.kotle.android.delegate.mmkvDelegate
import java.util.*

/**
 * 获取当前保存的语言
 */
private var kvCurrentLocalTag by mmkvDelegate("kotle_android_currentSaveLocalTag", "")

/**
 * 获取当前保存的语言
 */
fun getCurrentLocalTag(): String? {
    val value = kvCurrentLocalTag
    return value.ifBlank { null }
}

/**
 * 更新语言
 */
fun Context?.updateLocal(languageTag: String? = kvCurrentLocalTag): Context? {
    languageTag ?: return this
    this ?: return this
    kvCurrentLocalTag = languageTag
    return createConfigurationContext(updateLocal(resources.configuration, languageTag))
}

private fun updateLocal(configuration: Configuration, local: Locale): Configuration {
    configuration.setLocale(local)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        val locals = LocaleList(local)
        configuration.setLocales(locals)
    }
    return configuration
}

private fun updateLocal(configuration: Configuration, languageTag: String): Configuration {
    return updateLocal(configuration, Locale.forLanguageTag(languageTag))
}
